/*
 * Created: Author: Aléx Carvalho / Date: May 27, 2015
 * 
 * Changed: $Author: ac280593@gmail.com $ / $Date: 2015-06-11 01:31:49 -0300 (Thu, 11 Jun 2015) $
 */
package com.cpm.view.zk.field;

import com.cpm.entities.Information;
import java.util.Objects;
import javax.json.Json;
import org.zkoss.zk.ui.HtmlBasedComponent;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zk.ui.util.Clients;
import org.zkoss.zul.Div;

public class FormatTextField extends AbstractInputField<String> {

    private final Div div = new Div();
    private String value = "";

    public FormatTextField() {
    }

    @Override
    public HtmlBasedComponent getElement() {
        initComponents();
        return div;
    }

    public void setValue(Information information) {
        if (information != null) {
            setValue(information.getValue());
        }
        div.setWidgetListener("onBind", "formatTextField(this," + parseValueToJsonObject() + ");");
    }

    @Override
    public void setValue(String value) {
        this.value = value;

        if (div.getPage() != null) {
            Clients.evalJavaScript("setTextInFormatTextField(" + div.getUuid() + ", " + parseValueToJsonObject() + ")");
        }
    }

    @Override
    public String getValue() {
        return value;
    }

    public Information getInformation() {
        return new Information(value);
    }

    @Override
    public boolean isEnabled() {
        return true;
    }

    @Override
    public void setEnabled(boolean enable) {
        //TODO: implementar comtrole de habilitar e desabilitar FormatTextField
    }

    private String parseValueToJsonObject() {
        return Json.createObjectBuilder().add("value", Objects.toString(value, "")).build().toString();
    }

    private void initComponents() {

        div.setWidgetListener("onBind", "formatTextField(this," + parseValueToJsonObject() + ");");

        div.addEventListener(Events.ON_BLUR, (Event event) -> {
            value = event.getData() != null ? event.getData().toString() : "";
        });
    }

}
